<template>
  <div class="app" style="display: flex; flex-direction: column;">
    <vue-markdown :source="markdownContent" style="flex-grow: 1; min-height: 600px;"/>
    <div style="display: flex; flex-direction: row;">
      <textarea v-model="message" placeholder="请输入问题" style="min-width: 500px; flex-grow: 1"></textarea>
      <button style=" margin-left: 5px; font-size: 14px; padding: 5px;" :disabled="sendButtonDisabled" @click="ask()">发送</button>
    </div>
  </div>
</template>

<script>
import VueMarkdown from 'vue-markdown';
import {getBaseUrl} from '@/api/util/request';
export default {
  components: {VueMarkdown},
  data() {
    return {
      eventSource: null,
      message: "",
      markdownContent: '',
      sendButtonDisabled: false,
    };
  },
  beforeDestroy() {
    // 组件销毁时关闭连接（避免内存泄漏）
    if (this.eventSource) {
      this.eventSource.close();
    }
  },
  methods: {
    //提问
    ask() {
      this.markdownContent = "\n### " + this.message + "\n思考中。。。";
      this.connectSSE(this.message);
    },
    connectSSE(message) {
      this.sendButtonDisabled = true;
      // SSE 服务地址
      let tmpBaseUrl;
      if (getBaseUrl().trim().endsWith("/")) {
        tmpBaseUrl = getBaseUrl().trim().substring(0, getBaseUrl().length - 1);
      }
      else {
        tmpBaseUrl = getBaseUrl().trim();
      }
      const sseUrl = tmpBaseUrl + '/chat/stream?message=' + message;
      // 创建 EventSource 实例
      this.eventSource = new EventSource(sseUrl);
      // 监听消息事件
      this.eventSource.onmessage = (event) => {
        this.markdownContent = this.markdownContent + event.data;
      };
      // 监听自定义事件（可选）
      this.eventSource.addEventListener('customEvent', (event) => {
        console.log('Custom Event:', event.data);
      });
      this.eventSource.onabort = (event) => {
        this.sendButtonDisabled = false;
      };
      // 错误处理（自动重连）
      this.eventSource.onerror = (error) => {
        this.eventSource.close();
        this.sendButtonDisabled = false;
      };
    }
  }
};
</script>
